<template>
	<view class="content">
		<!-- #ifndef H5 -->
			<recording ref="recordingH5" @success='recordingSuccess' @fail='recordingFail' v-if="inputType === 'audio'"></recording>
		<!-- #endif -->
		<!-- #ifdef APP -->
			<appRecording ref="recordingApp" @success='recordingSuccess' @fail='recordingFail' v-if="inputType === 'audio'"></appRecording>
		<!-- #endif -->
		<!-- <view class="switchBtn" @click="toCreativeCenter">
			<view class="leftBubble">
				<bubble align='center' :customStyle='{width:"100%",height: "92rpx",display:"flex",justifyContent:"center",alignItems:"center"}'>
					<text class="big">点击切换更多</text>
				</bubble>
			</view>
			<image class="logo" src="../../static/logo.png"></image>
		</view> -->
		<!-- #ifdef APP -->
		<view class="space"></view>
		<!-- #endif -->
		<!-- 快速导航 -->
		<view class="quickGuide">
			<view class="hello">HI！快来问我吧~</view>
			<view class="item" v-for='(item,index) in fastList' :key="index" @click="fastAsk(item)">
				<view class="itemLeft">
					{{item}}
				</view>
				<view class="icon">
					<u-icon name="arrow-right" size="15" color="#fff"></u-icon>
				</view>
			</view>
		</view>
		<!-- 会话区域 -->
		
		<view class="talkList">
			<view class="talkItem" :class="getDirection(item.from)" @longpress="copy(item)" v-for="(item,index) in historyTalk" :key="index">
				<bubble @stop='aiStop' :showStop="item.from === 'ai' && index === historyTalk.length - 1 && loading" :type="item.from === 'me' ? 'color' : 'black'" :direction="getDirection(item.from)" :custom-style="{padding: '20rpx 30rpx'}">
				{{item.text}} <view v-if="item.userStop == 1" style="color: red;font-size: 22rpx">用户暂停AI</view>
				</bubble>
			</view>
			<view class="talkItem left" v-if="aiThinking">
				<bubble type="black" direction='left' :custom-style="{padding: '20rpx 30rpx',display:'flex',justifyContent:'flex-start',alignItems:'center'}">
					<image src="../../static/loading.png" mode="" class="loading"></image> AI思考中...
				</bubble>
			</view>
		</view>
		<view id="bottom"></view>
		<view class="inputArea" @click="inputClick">
			<image class="inputIcon" @click="exchangeInput" :src="`../../static/${inputType}.png`"></image>
			<view class="audioBtn" v-if="inputType === 'audio'" @longpress="startRecord" @touchend="stopRecord">按住 说话</view>
			<input type="text" :disabled="loading" placeholder="输入你想问的..." @confirm="askAi" v-model="text" class="keyboard" v-else>
		</view>
		<openVip></openVip>
		<updateModal></updateModal>
	</view>
</template>

<script>
	import config from '@/utils/config.js'
	import ioSocket from '@/utils/ioSocket.js'
	export default {
		data() {
			return {
				fastList: [],
				inputType: 'keyboard',//输入类型 keyboard audio
				text:'',// 输入的文字
				loading:false,//正在请求ai回话
				historyTalk: [],
				scrollTop: 0,
				aiThinking: false,
				socketDistance: '',//socket实例
			}
		},
		mounted() {
			
		},
		onLoad() {
			this.getWelcome()
		},
		onShow() {
			this.getHistory()
		},
		onPageScroll(data) {
			this.scrollTop = data.scrollTop
			// if(data.scrollTop < 50) {
			// 	// 认为是触顶 请求聊天记录
			// }
		},
		watch: {
			historyTalk: {
				deep: true,
				handler() {
					clearTimeout(this.st)
					// 回话更新，滚动到最新位置
					this.st = setTimeout(() => {
						uni.pageScrollTo({
							selector: '#bottom',
							// duration: 0
						})
					},100)
				}
			}
		},
		methods: {
			copy(item) {
				uni.setClipboardData({
					data: item.text
				})
			},
			// 获取历史回话记录
			getHistory() {
				this.historyTalk = uni.getStorageSync('historyTalk') || []
				this.$nextTick(() => {
					uni.pageScrollTo({
						selector: '#bottom',
						duration: 0
					})
				})
			},
			// 快捷问询
			fastAsk(item) {
				this.text = item;
				this.askAi()
			},
			isEnOrNum(str) {
				return str.match("[a-zA-Z0-9]+")   //判断英文和数字
			},
			// 停止ai输出
			aiStop() {
				const currentLength = this.historyTalk.length;
				// #ifdef APP
				this.socketDistance.close({code:1000})
				this.historyTalk[currentLength - 1].userStop = 1
				// #endif
				// #ifdef H5
				this.socketDistance = null
				this.loading = false;
				this.historyTalk[currentLength - 1].userStop = 1
				// #endif
			},
			// 开启socket
			openSocket(text) {
				this.loading = true;
				const currentLength = this.historyTalk.length;
				ioSocket({
					data: {
						context: text
					},
					success: data => {
						this.aiThinking = false
						if(currentLength === this.historyTalk.length) {
							this.historyTalk.push({
								text: data,
								status: 'success',
								from: 'ai'
							})
						}else {
							this.historyTalk[currentLength].text = `${this.historyTalk[currentLength].text}${this.isEnOrNum(data) ? ` ${data}` : data}`
						}
						uni.setStorageSync('historyTalk',this.historyTalk)
					},
					close: msg => {
						this.loading = false;
						this.aiThinking = false
						console.log('close callback')
					},
					fail: err => {
						this.loading = false;
						this.aiThinking = false
					},
					socketDistance: distance => {
						this.socketDistance = distance
					}
				})
			},
			parseString(text) {
				// text = text.slice(1,text.length - 1)
				// const arr = text
				text = JSON.parse(text)
				console.log(text,'json')
			},
			recordingFail() {
				uni.hideLoading()
				this.loading = false;
			},
			recordingSuccess(text) {
				uni.hideLoading()
				this.text = text;
				this.loading = false;
				this.askAi()
			},
			// 向ai问话
			async askAi() {
				if(this.loading) {
					uni.showToast({
						title:"AI正在回答，请稍后~",
						icon: 'none'
					})
					return
				}
				const have = await this.$checkAuth()
				console.log(123)
				if(!have) return;
				setTimeout(() => {
					this.text = '';
				},200)
				this.aiThinking = true;
				this.historyTalk.push({
					text: this.text,
					status: 'success',
					from:'me'
				})
				// #ifdef APP
				this.openSocket(this.text)
				// #endif
				// #ifdef H5
				this.openStream(this.text)
				// #endif
			},
			openStream(text) {
				this.loading = true;
				const currentLength = this.historyTalk.length;
				this.socketDistance = currentLength
				this.$stream({
					url:'/api/v1/miletus/word/ai/chat/base/stream',
					data: {
						context: this.text
					},
					success: res => {
						console.log(res,'reee')
						this.aiThinking = false;
						if(currentLength === this.historyTalk.length) {
							this.historyTalk.push({
								text: res,
								status: 'success',
								from: 'ai'
							})
						}else {
							if(this.socketDistance !== currentLength) return;
							this.historyTalk[currentLength].text = `${this.historyTalk[currentLength].text}${this.isEnOrNum(res) ? ` ${res}` : res}`
						}
					},
					fail: err => {
						console.log(err,'err')
						this.historyTalk[this.historyTalk.length - 1].status = 'fail'
						this.loading = false;
						this.aiThinking = false;
					},
					closed: () => {
						uni.setStorageSync('historyTalk',this.historyTalk)
						this.loading = false;
						this.aiThinking = false;
					}
				})
			},
			getWelcome() {
				console.log(111)
				this.$request({
					url:'/api/v1/miletus/word/ai/welcome/remind',
					method:'get'
				}).then(res => {
					this.fastList = res;
				})
			},
			// 创作中心
			toCreativeCenter() {
				uni.navigateTo({
					url: '/pages/creativeCenter/creativeCenter'
				})
			},
			inputClick() {
				if(this.loading) {
					uni.showToast({
						title: 'AI正在回答，请稍后',
						icon: 'none'
					})
				}
			},
			// 长按启用麦克风说话
			startRecord() {
				if(this.loading) return;
				this.loading = true;
				uni.showLoading({
					title: '讲话中...'
				})
				// #ifdef H5
				this.$refs.recordingH5.start()
				// #endif
				// #ifdef APP
				this.$refs.recordingApp.start()
				// #endif
			},
			// 录音完毕
			stopRecord() {
				this.loading = false;
				// #ifdef H5
				this.$refs.recordingH5.stop()
				// #endif
				// #ifdef APP
				this.$refs.recordingApp.stop()
				// #endif
			},
			// 切换输入模式
			exchangeInput() {
				this.inputType = this.inputType === 'keyboard' ? 'audio' : 'keyboard'
			},
			getDirection(from) {
				return from === 'me' ? 'right' : 'left'
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		padding: 60rpx 30rpx 30rpx;
		.switchBtn {
			background-color: $my-bg;
			padding: 30rpx 60rpx 0 30rpx;
			height: 160rpx;
			position: fixed;
			left: 0;
			top: 0;
			right: 0;
			z-index: 2;
			margin: auto;
			display: flex;
			justify-content: flex-start;
			.leftBubble {
				align-self: flex-end;
				flex: 1;
				margin-right: 30rpx;
				padding-bottom: 30rpx;
			}
			.big {
				font-size: 36rpx;
				color: #000002;
				font-weight: 600;
				line-height: 1;
			}
			.logo {
				width: 150rpx;
				height: 160rpx;
				flex-shrink: 0;
			}
		}
		.space {
			padding-top: var(--window-top);
			margin-bottom: 30rpx;
		}
		.quickGuide {
			background-color: #2A2B3D;
			border-radius: 20rpx;
			padding: 40rpx 20rpx;
			.hello {
				font-size: 35rpx;
				color: #FFFFFF;
				margin-bottom: 10rpx;
			}
			.item {
				padding: 20rpx 0;
				display: flex;
				justify-content: flex-start;
				align-items: center;
				.itemLeft {
					flex: 1;
					font-size: 30rpx;
					color: #FFFFFF;
					white-space: nowrap;
					text-overflow: ellipsis;
					overflow: hidden;
				}
				.icon {
					width: 30rpx;
					flex-shrink: 0;
				}
			}
		}
		$inputHeight: 146rpx;
		.talkList {
			padding: 35rpx 0 $inputHeight;
			.talkItem {
				display: flex;
				&+.talkItem {
					margin-top: 35rpx;
				}
				&.left {
					padding-right: 20%;
					justify-content: flex-start;
				}
				&.right {
					
					padding-left: 20%;
					justify-content: flex-end;
				}
				.loading {
					$s: 40rpx;
					width: $s;
					height: $s;
					margin-right: 20rpx;
					animation: roll infinite 1.5s linear;
				}
				@keyframes roll {
					from {
						transform: rotateZ(0);
					}
					to {
						transform: rotateZ(360deg);
					}
				}
			}
		}
		.inputArea {
			height: $inputHeight;
			background: linear-gradient(0deg, rgba(26, 28, 47, 0.7)  0%, rgba(24, 24, 36, 0.7) 100%);
			position: fixed;
			width: 100%;
			overflow: hidden;
			box-sizing: border-box;
			left: 0;
			bottom: var(--window-bottom);
			padding: 0 30rpx;
			display: flex;
			justify-content: flex-start;
			align-items: center;
			.inputIcon {
				$s: 65rpx;
				width: $s;
				height: $s;
				margin-right: 20rpx;
				flex-shrink: 0;
			}
			$h: 76rpx;
			.audioBtn,.keyboard {
				flex: 1;
				height: $h;
				border-radius: math.div($h,2);
				box-shadow: 0px 15px 27px 0px rgba(0,0,0,0.25);
			}
			.audioBtn {
				background: linear-gradient(0deg, #59E785 0%, #4AEBE9 100%);
				line-height: $h;
				text-align: center;
				color: #171717;
				font-size: 36rpx;
			}
			.keyboard {
				overflow: hidden;
				box-sizing: border-box;
				background: #1A1D30;
				border: 1px solid #58E789;
				padding: 0 30rpx;
				font-size: 36rpx;
			}
		}
	}

</style>
